#! /usr/bin/env python
"""KIEL2 data format
Copyright (c) 2011-2013 Christian T. Steigies <steigies@physik.uni-kiel.de>

This module offers functions to read NMDA data as used in KIEL2
and return data in the format as used by NMDB."""

__author__ = "Christian T. Steigies <steigies@physik.uni-kiel.de>"
__license__ = "GPL License"

#import os
import datetime

import MySQLdb # python-mysqldb
#http://docs.python.org/library/sqlite3.html
#from sqlite3 import dbapi2 as sqlite3

from nmdb.tools.configtool import parse_config
from nmdb.nm64.nm64_data import NM64Data, row2insert

#__all__ = ["read_1m", "read_1h"]

## --------------------------------------------------------------------------
class Kiel2(NM64Data):
    def __init__(self, station, year, month, day, hour):
        """read 1hour of data for station kiel2
        """

        # TODO: define rcfile from options?
        rcfile = "/home/kermes/steigies/.nmdbrc"
        NM64Data.__init__(self, station, year, month, day, hour)

        mode = "nmdadb"
        (username, password, hostname, dbname, portnumber) = parse_config(rcfile, station.lower(), mode)

        db = MySQLdb.connect(host=hostname, port=portnumber, db=dbname, user=username, passwd=password)
        con = db.cursor()

        # use columns in the order of NM64 BIN format
        cols = "start_date_time, ch01, ch02, ch03, ch04, ch05, ch06, ch07, ch08, ch09, ch10, ch11, ch12, ch13, ch14, ch15, ch16, ch17, ch18, atmPressure, temp_1, temp_2, hv1, hv2, hv3, 0, 0"
        #cols = "start_date_time, ch01, ch02, ch03, ch04, ch05, ch06, ch07, ch08, ch09, ch10, ch11, ch12, ch13, ch14, ch15, ch16, ch17, ch18, atmPressure"

        # get one hour of data
        start = self.dt()
        stopp = self.dt() + datetime.timedelta(minutes=59)
        querystring = ("SELECT %s FROM binTable WHERE start_date_time >= \"%s\" AND "
                       "start_date_time <= \"%s\" ORDER BY start_date_time ASC;"
                       ) % (cols, start, stopp)
        #print querystring
        con.execute(querystring)

        # store data in internal sqlite database
        rows = con.fetchall()
        for row in rows:
            #print row
            querystring = row2insert(row)
            #print "query", querystring
            self._c.execute(querystring)
        #self._c.execute('''INSERT INTO data VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''', data)
        #            (datetime timestamp, ch01 int, ch02 int, ch03 int, ch04 int, ch05, ch06 int, ch07 int, ch08 int, ch09 int, ch10 int, ch11 int, ch12 int, ch13 int, ch14 int, ch15 int, ch16 int, ch17 int, ch18 int, hv1 int, hv2 int, hv3 int, temp1 int, temp2 int, pressure int)''')
        #self.__conn.commit()

    def _value(self, minute):
        """return values as read in"""
        
        dt = str(datetime.datetime(self._year, self._month, self._day, self._hour, minute, 0))
        cols = "ch01, ch02, ch03, ch04, ch05, ch06, ch07, ch08, ch09, ch10, ch11, ch12, ch13, ch14, ch15, ch16, ch17, ch18, pressure"
        querystring = "SELECT %s FROM data WHERE datetime == \"%s\"" % (cols, dt)
        self._c.execute(querystring)
        row = self._c.fetchone() # should return only one line, or None
        #print "SQL:", row
        if row:
            return row
        else:
            return None

## --------------------------------------------------------------------------

if __name__ == "__main__":
    print "This is the KIEL2 module for NMDB."

